package librairies.liste.list;

import librairies.liste.interfaces.IIterateur;
import librairies.liste.interfaces.IListe;
import librairies.liste.interfaces.IListeE;

/**
 * Definition dans de la liste DCE
 * 
 * @author mlozach
 * @param <F> type de l'elements dans le liste
 */
public class ListeDCE<F extends Comparable<F>> extends ListeDC<F> implements IListeE<F> 
{	
	/**
	 * constructeur par default
	 */
	public ListeDCE()
	{
		super();
	}

	/**
	 * constructeur par recopie
	 * @param init liste des elements initiaux
	 */
	public ListeDCE(IListe<F> init) 
	{
		super(init);
	}
		
	@Override
	public void reverse()
	{
		if(this.size()  <= 1)
		{
			return;
		}
		
		F tmp;
		
		for(int i = 0; i < this.size() / 2 ; ++i)
		{
			tmp = this.get(i);
			this.set(i, this.get(this.size() - i - 1));
			this.set(this.size() - i - 1, tmp);
		}
 	}

	@Override
	public Object[] toArray() 
	{
		Object[] tab = new Object[this.size()];
		
		if(this.isEmpty())
		{ 
			return tab;
		}
		
		for(int i = 0; i < this.size(); ++i)
		{
			tab[i] = this.get(i);
		}
		
		return tab;
	}
	
	@Override
	public IIterateur<F> iterator() 
	{
		IterateurDCE<F> tmp = new IterateurDCE<F>(this);
		
		return tmp;
	}

	@Override
	public F max() throws java.util.NoSuchElementException 
	{
		if(this.isEmpty())
		{
			return null;
		}
		
		F tmp = this.getTete().getValeur();
		
		if(this.size() == 1)
		{
			return tmp;
		}
		
		for(int i = 0; i < this.size(); ++i)
		{
			if(tmp.compareTo(this.get(i)) < 0)
			{
				tmp = this.get(i);
			}
		}

		return tmp;
	}

	@Override
	public F min() throws java.util.NoSuchElementException 
	{
		if(this.isEmpty())
		{
			return null;
		}
		
		F tmp = this.getTete().getValeur();
		
		if(this.size() == 1)
		{
			return tmp;
		}
		
		for(int i = 0; i < this.size(); ++i)
		{
			if(tmp.compareTo(this.get(i)) > 0)
			{
				tmp = this.get(i);
			}
		}

		return tmp;
	}

	@Override
	public IListeE<F> subSet(F borneMin, F borneMax) 
	{
		if(borneMin == null || borneMax == null)
		{
			return null;
		}
		
		IListeE<F> tmp = new ListeDCE<F>();
		
		for(int i = 0; i < this.size(); ++i)
		{
			if(this.get(i).compareTo(borneMin) >= 0)
			{
				if(this.get(i).compareTo(borneMax) < 0)
				{
					tmp.add(this.get(i));
				}
			}
		}
			
		return tmp;
	}

	@Override
	public void sort() 
	{
		boolean ok = true;
		F tmp;
		
		while(ok)
		{
			ok = false;
			
			for(int i = 0; i < this.size() - 1; ++i)
			{
				if(this.get(i).compareTo(this.get(i + 1)) > 0)
				{
					tmp = this.get(i);
					this.set(i, this.get(i + 1));
					this.set(i + 1, tmp);
					
					ok = true;
				}
			}
		}
	}
}